package com.telenav.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketConnection implements NetworkConnection {

	private Socket socket;

	private InetSocketAddress address;

	private boolean timeout;

	SocketConnection(InetSocketAddress address, boolean timeout) {
		socket = new Socket();
		this.address = address;
		this.timeout = timeout;
	}

	public String getAddress() throws IOException {
		return this.socket.getInetAddress().getHostName();
	}

	public String getLocalAddress() throws IOException {
		return this.socket.getLocalAddress().getHostName();
	}

	public int getLocalPort() throws IOException {
		return this.socket.getLocalPort();
	}

	public int getPort() throws IOException {
		return this.socket.getPort();
	}

	public InputStream openInputStream() throws IOException
    {
        return this.socket.getInputStream();
    }

    public OutputStream openOutputStream() throws IOException
    {
        if(timeout)
        {
            socket.setSoTimeout(30 * 1000);
            socket.connect(address, 30 * 1000);
        }
        else
        {
            socket.connect(address);
        }
        
        return this.socket.getOutputStream();
    }

	public void close() throws IOException {
		this.socket.shutdownInput();
		this.socket.shutdownOutput();
		this.socket.close();
	}

}
